/*
 * @Date: 2022-06-12 17:23:43
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-07-01 10:57:34
 * @FilePath: \taro-music-learn\src\utils\request.ts
 * @Description: something
 */
import Taro from "@tarojs/taro";
import store from "@/store";
import {
  requestPending,
  requestFulfilled,
  requestRejectd
} from "@/store/loading";
type MethodType = "POST" | "GET" | "PUT" | "DELETE";
const cookie = Taro.getStorageSync("cookies");
const service = (url: string, method: MethodType = "GET", data?: {}) => {
  const timeStamp = Date.now();
  if (cookie) {
    console.log("有cookie");
    data = { ...data, cookie, timeStamp };
  } else {
    console.log("无cookie");
    data = { ...data, timeStamp };
  }
  store.store.dispatch(requestPending());
  const res = Taro.request({
    url: url.indexOf("http") !== -1 ? url : "http://sailor.cool:1234" + url,
    method,
    data,
    header: {
      "content-type": "application/json"
    },
    mode: "cors",
    success: () => {
      store.store.dispatch(requestFulfilled());
    },
    fail: error => {
      store.store.dispatch(requestRejectd());
    }
  });
  return res;
};

export const PromiseFormat = (data: { code: 200; data: any }) => {
  if (data.code === 200) {
    return Promise.resolve(data);
  } else {
    return Promise.reject(data);
  }
};
export { service as request1 };
